package com.bytz.modules.cms.reseller.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytz.common.exception.BytzBootException;
import com.bytz.common.system.query.QueryGenerator;
import com.bytz.modules.cms.order.constant.OrderConstants;
import com.bytz.modules.cms.reseller.entity.CouponReseller;
import com.bytz.modules.cms.reseller.entity.Reseller;
import com.bytz.modules.cms.reseller.mapper.CouponResellerMapper;
import com.bytz.modules.cms.reseller.model.CouponResellerModel;
import com.bytz.modules.cms.reseller.service.IAdminCouponResellerService;
import com.bytz.modules.cms.reseller.service.IAdminResellerService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class AdminCouponResellerServiceImpl extends ServiceImpl<CouponResellerMapper,CouponReseller> implements IAdminCouponResellerService {

    @Autowired
    private IAdminResellerService adminResellerService;

    private static final  LocalDateTime EffectEndTime=LocalDateTime.of(9999,1,1,0,0,0);


    @Transactional
    @Override
    public void addCouponReseller(CouponResellerModel couponReseller) {
        for (int i = 0; i < couponReseller.getAddCount(); i++) {
            couponReseller.setId(null);
            couponReseller.setStatus(Integer.valueOf(OrderConstants.CouponType.ENABLE));
            if (couponReseller.getEffectEndTime() == null) {
                couponReseller.setEffectEndTime(EffectEndTime);
            }
            this.save(couponReseller);
        }
    }

    @Transactional
    @Override
    public void importExcel(List<CouponReseller> importData) {
        //进行Excel数据检查
        importData.forEach(this::checkImportData);
        //获取要给予优惠卷的 供应商 名称
        Set<String> resellerNames = importData.stream()
                .map(CouponReseller::getResellerName)
                .collect(Collectors.toSet());
        //向cms_reseller表中，一次性查询供应商的信息
        if (CollectionUtils.isEmpty(resellerNames)) {
            throw new BytzBootException("数据有误");
        }
        List<Reseller> resellers = adminResellerService.findByResellerName(resellerNames);
        //Key：供应商名称 Value：供应商ID
        Map<String, String> resellerMap = resellers.stream().collect(Collectors.toMap(Reseller::getResellerName, Reseller::getId));
        //对每个优惠卷赋值对应的供应商ID
        importData.forEach(couponReseller -> {
            String id = resellerMap.get(couponReseller.getResellerName());
            if (StringUtils.isBlank(id)) {
                throw new BytzBootException("Excel中"+couponReseller.getResellerName()+"对应的供应商未找到，导入失败");
            }
            couponReseller.setResellerId(id);
            couponReseller.setStatus(Integer.valueOf(OrderConstants.CouponType.ENABLE));
            if (couponReseller.getEffectEndTime() == null) {
                couponReseller.setEffectEndTime(EffectEndTime);
            }
        });
        //批量保存
        saveBatch(importData);
    }

    /**
     * 检查解析后的Excel_List数据
     */
    private void checkImportData(CouponReseller c) {
        if (StringUtils.isBlank(c.getCouponName())) {
            throw new BytzBootException("该Excel表里有优惠券名称未填");
        } else if (StringUtils.isBlank(c.getResellerName())) {
            throw new BytzBootException("该Excel表里有经销商名称没有填写");
        } else if (c.getEffectStartTime() == null) {
            throw new BytzBootException("未填写优惠券起始时间");
        } else if (c.getMinPrice() == null) {
            throw new BytzBootException("未填写到达满减要求的金额");
        } else if (c.getDiscountPrice()==null) {
            throw new BytzBootException("未填写满减金额");
        }
    }

    @Override
    public CouponReseller getModelById(String id) {
        CouponReseller byId = this.getById(id);
        if (byId == null) {
            throw new BytzBootException("该优惠券不存在");
        }
        if (EffectEndTime.equals(byId.getEffectEndTime())) {
            byId.setEffectEndTime(null);
        }
        return byId;
    }

    @Override
    public void getCouponResellerPage(IPage<CouponReseller> page, CouponReseller couponReseller, HttpServletRequest req) {
        LocalDateTime searchEffectEndTime = couponReseller.getEffectEndTime();
        LocalDateTime searchEffectStartTime = couponReseller.getEffectStartTime();
        couponReseller.setEffectEndTime(null);
        couponReseller.setEffectStartTime(null);
        LambdaQueryWrapper<CouponReseller> queryWrapper = QueryGenerator.initLambdaQueryWrapper(couponReseller,req.getParameterMap());
        queryWrapper
                .ge(searchEffectStartTime != null, CouponReseller::getEffectEndTime, searchEffectStartTime)
                .le(searchEffectEndTime!= null, CouponReseller::getEffectStartTime, searchEffectEndTime);
        this.page(page, queryWrapper);
        List<CouponReseller> couponResellerList = page.getRecords();
        couponResellerList.stream()
                .filter(c -> EffectEndTime.equals(c.getEffectEndTime()))
                .forEach(c -> c.setEffectEndTime(null));
    }
}
